<template>
  <basic-container class="app-container">
    <div class="filter-container">
      <el-form ref="form" :model="deliveryFrom" label-width="80px">
        <div class="deliverysflex">
          <el-form-item label="后台单号">
            <el-input v-model.trim="deliveryFrom.xmbzNo" size="small" width='120px' clearable @keyup.enter.native="handleFilter">
            </el-input>
          </el-form-item>
          <el-form-item label="配送员">
            <el-input v-model.trim="deliveryFrom.delivery" size="small" width='120px' clearable @keyup.enter.native="handleFilter">
            </el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleFilter" size="small" plain icon="el-icon-search">查询</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div class="main">
      <div class="map-container" :style="{'height':curHeight+'px'}">
        <XmMap ref="xmMap" style="width: 98%;height: 100%;"></XmMap>
      </div>
    </div>
    <div class="markTips" v-if='markTips'>当前配送员暂无配送单</div>
  </basic-container>
</template>
<link rel="stylesheet" href="https://a.amap.com/jsapi_demos/static/demo-center/css/demo-center.css" />
<script src="https://a.amap.com/jsapi_demos/static/demo-center/js/demoutils.js"></script>
<script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script>
<script>
  import cake from '@/assets/image/cake.png'
  import VueAMap from 'vue-amap'
  import {
    getWorkOnDeliverySituation, //配送情况当天的
    getOrderWorkOnDeliverySituation,
  } from "@/api/orderDispatch";
  var mapSelectData = [];
  export default {
    data() {
      return {
        cake,
        deliveryFrom: {
          // deptId: '', //城市id
          xmbzNo: '', //后台单号
          delivery: '' //配送员
        },
        deliveryData: [],
        markTips: false,
        cityareaName: '',
        curHeight: 0
      }

    },
    mounted() {
      var saberareaIds = JSON.parse(localStorage.getItem('saber-areaId'));
      this.cityareaId = saberareaIds['content']
      var saberareaName = JSON.parse(localStorage.getItem('saber-areaname'));
      this.cityareaName = saberareaName['content']
      // this.getMapaddress(this.cityareaName, this.$refs.xmMap.map);
      this.beforeMount(100)
      this.getlist();
      window.addEventListener("keydown", this.keyupEnter);
    },
    destroyed() {
      window.removeEventListener("keydown", this.keyDown, false);
    },
    methods: {
      keyupEnter() {
        if (window.event.keyCode == 13) {
          // this.handleFilter(); // 查询事件
          this.deliveryFrom.deptId = this.cityareaId;
          getWorkOnDeliverySituation(this.deliveryFrom).then(res => {
            this.deliveryData = res.data.data;
            if (this.deliveryData && this.deliveryData.length > 0) {
              setTimeout(() => {
                this.listLoading = false;
                this.getShowmap(this.deliveryData, this.$refs.xmMap.map);
                this.getMapaddress(this.cityareaName, this.$refs.xmMap.map);
              }, 0.5 * 1000);
            } 
          })
        }
      },
      //如果页面有keep-alive缓存功能，这个函数会触发
      activated() {
        window.addEventListener("keydown", this.keyupEnter);
      },
      deactivated() {
        window.removeEventListener("keydown", this.keyupEnter);
      },
      // 查询
      handleFilter() {
        this.getlist();
      },
      //获取屏幕
      beforeMount(height) {
        var h = document.documentElement.clientHeight || document.body.clientHeight;
        this.curHeight = h - height; //减去页面上固定高度height
      },
      getlist() {
        this.deliveryFrom.deptId = this.cityareaId;
        getWorkOnDeliverySituation(this.deliveryFrom).then(res => {
          this.deliveryData = res.data.data;
          if (this.deliveryData && this.deliveryData.length > 0) {
            setTimeout(() => {
              this.listLoading = false;
              this.getShowmap(this.deliveryData, this.$refs.xmMap.map);
              this.getMapaddress(this.cityareaName, this.$refs.xmMap.map);
            }, 0.5 * 1000);
          } else {
            this.$message({
              showClose: true,
              message: "暂无数据",
              type: 'warning'
            });
          }
        })
      },
      //根据城市获取地图位置
      getMapaddress(name, mapObj) {
        var MSearch;
        // var mapObj = this.$refs.xmMap.map;
        // mapObj.setZoomAndCenter(14, [poiArr[0].location.lng, poiArr[0].location.lat]);
        mapObj.plugin(
          ["AMap.PlaceSearch"],
          () => {
            // mapObj.addControl(new AMap.ToolBar())
            // mapObj.addControl(new AMap.Scale())
            MSearch = new AMap.PlaceSearch({
              //构造地点查询类
              city: '北京市' //城市
            });
            AMap.event.addListener(MSearch, "complete", this.keywordSearch_CallBack) //返回地点查询结果
            MSearch.search(name); //关键字查询
          }
        );
      },
      keywordSearch_CallBack(data) {
        var mapObj = this.$refs.xmMap.map;
        var poiArr = data.poiList.pois
        var resultCount = poiArr.length
        this.poiArr = poiArr; //左边要渲染的数据
        mapObj.setFitView()
        mapObj.setZoomAndCenter(10, [poiArr[0].location.lng, poiArr[0].location.lat]);
        this.newcenter = [poiArr[0].location.lng, poiArr[0].location.lat];
      },
      // 地图 -----------------------------
      getShowmap(items, map) {
        map.clearMap();
        // var map = new AMap.Map("mapcontainer");
        let that = this;
        var markersSelection = [];
        for (var i = 0; i < items.length; i++) {
          if (items[i].colourStatus == 0) {
            //未分配 绿色
            var myIcon = new AMap.Marker({
              position: [
                items[i].deliveryLongitude,
                items[i].deliveryLatitude
              ],
              icon: "http://api.xiongmaodangao.com/images/xmdg_green.png"
            });
            myIcon.setLabel({
              //修改label相对于maker的位置
              offset: new AMap.Pixel(-20, -20),
              content: `<div  class='mapcontainter' >${items[i].delivery}</div>`,
              backgroundColor: "0.00001"
            });
            map.add(myIcon);

            myIcon.on("click", function() {
              that.$message({
                showClose: true,
                message: "该配送员今天未分配订单或分配订单后该订单未入库",
                type: 'warning'
              });
            });

          } else if (items[i].colourStatus == 1) {
            //已分配 蓝色
            let that = this;
            var myIcon2 = new AMap.Marker({
              position: [
                items[i].deliveryLongitude,
                items[i].deliveryLatitude
              ],
              icon: "http://api.xiongmaodangao.com/images/xmdg_blue.png"
            });
            myIcon2.setLabel({
              //修改label相对于maker的位置
              offset: new AMap.Pixel(-20, -20),
              content: `<div class='mapcontainterblue' >${items[i].delivery}/配送中</div>`,
              backgroundColor: "0.00001"
            });
            myIcon2.item = items[i];
            map.add(myIcon2);
            myIcon2.on("click", function(items) {
              var eid = myIcon2.item.id;
              if (mapSelectData.indexOf(eid) == -1) { //看看里面有没有这个点如果没有，就改点的颜色为选中状态，并把订单号记录进去
                this.setIcon("http://api.xiongmaodangao.com/images/xmdg_red.png");
                that.addMapList(eid);
                that.getWorkOnDeliverySituations(this.item, map, mapSelectData.indexOf(eid))
              } else { //说明有这个单，就取消掉这个单，把点的颜色改为没有选中的状态，green
                //去掉数据
                that.delMapList(eid);
                that.getWorkOnDeliverySituations(this.item, map, mapSelectData.indexOf(eid))
                this.setIcon("http://api.xiongmaodangao.com/images/xmdg_blue.png");
                that.getlist()

              }
            })

          }
        }
      },
      tip(orderData, amap) {
        var p2 = [orderData.orderLongitude, orderData.orderLatitude];
        //构建信息窗体中显示的内容
        var info = [];
        getOrderWorkOnDeliverySituation({
          deptId: this.cityareaId,
          xmbzNo: orderData.xmbzNo
        }).then(res => {
          var dis = AMap.GeometryUtil.distance([res.data.data.deliveryLongitude, res.data.data.deliveryLatitude], [
            res.data.data.orderLongitude, res.data.data.orderLatitude
          ]);
          dis = parseInt(dis);
          var time = '';
          var text = "距离目的地还剩：" + dis + "米";
          if (dis < 10) {
            text = "已到达目的地附近";
          }
          if (res.data.data.surplusTime == '00小时00分钟') {
            info.push("<div style=\"padding:7px 0px 0px 0px;\"><h4>" + orderData.xmbzNo + "/" + orderData.deliveryEndTime + "</h4>");
            info.push("<h4>" + orderData.receiverAddress + "</h4>");
            info.push("<p class='input-item'>" + text + "</p>");
            info.push("距离配送时间还剩:<span class='input-item'>" + '已超过配送时间' + "</span></div></div>");
          } else {
            info.push("<div style=\"padding:7px 0px 0px 0px;\"><h4>" + orderData.xmbzNo + "/" + orderData.deliveryEndTime + "</h4>");
            info.push("<h4>" + orderData.receiverAddress + "</h4>");
            info.push("<p class='input-item'>" + text + "</p>");
            info.push("距离配送时间还剩:<span class='input-item'>" + res.data.data.surplusTime + "</span></div></div>");

          }
          const infoWindow = new AMap.InfoWindow({
            content: info.join("") //使用默认信息窗体框样式，显示信息内容
          });
          infoWindow.open(amap, amap.getCenter());

        })
      },
      getmapcontainer(cakeLnglat, map) {
        for (let f = 0; f < cakeLnglat.length; f++) {
          map.plugin(["AMap.Driving"], function() {
            var driving = new AMap.Driving({
              map: map
            })
            //地点关键字+ 驾车路线规划
            driving.search(new AMap.LngLat(cakeLnglat[f].deliveryLongitude, cakeLnglat[f].deliveryLatitude), new AMap
              .LngLat(cakeLnglat[f].orderLongitude, cakeLnglat[f].orderLatitude),
              function(
                status, result) {
                // result 即是对应的驾车导航信息，相关数据结构文档请参考  https://lbs.amap.com/api/javascript-api/reference/route-search#m_DrivingResult
                if (status === 'complete') {
                  console.log(result)
                } else {
                  console.log('获取驾车数据失败：' + result);
                }
              });
            map.add(driving);
          })
        }
      },
      getWorkOnDeliverySituations(item, map, eid) {
        var self = this;
        getWorkOnDeliverySituation({
          deptId: this.cityareaId, //城市id
          delivery: item.delivery, //配送员
          xmbzNo: this.deliveryFrom.xmbzNo,
        }).then(res => {
          this.deliveryCakeData = res.data.data;
          for (var i = 0; i < this.deliveryCakeData.length; i++) {
            const orderData = this.deliveryCakeData[i]
            var markers = new AMap.Marker({
              position: new AMap.LngLat(this.deliveryCakeData[i].orderLongitude, this.deliveryCakeData[
                i].orderLatitude), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
              receiverAddress: this.deliveryCakeData[i].receiverAddress,
              xmbzNo: this.deliveryCakeData[i].xmbzNo,
              delivery: this.deliveryCakeData[i].delivery,
              deliveryEndTime: this.deliveryCakeData[i].deliveryEndTime,
              icon: this.cake,
              size: new AMap.Size(28, 36), //图标所处区域大小
            });
            // ;
            markers.item = this.deliveryCakeData[i];
            if (eid == '0') {
              markers.on('click', function(ev) {
                self.tip(orderData, map);
              });

              self.getmapcontainer(res.data.data, map)
              map.add(markers);
            } else {
              map.remove(markers);
            }
          }
        })

      },

      //添加
      addMapList(id) {
        mapSelectData.push(id);
      },
      //删除
      delMapList(id) {
        var index = mapSelectData.indexOf(id);
        if (index > -1) {
          mapSelectData.splice(index, 1);
        }
      },
    }
  }
</script>

<style lang='scss' scoped>
  #panel {
    position: fixed;
    background-color: white;
    max-height: 90%;
    overflow-y: auto;
    top: 10px;
    right: 10px;
    width: 280px;
  }

  #panel .amap-call {
    background-color: #009cf9;
    border-top-left-radius: 4px;
    border-top-right-radius: 4px;
  }

  #panel .amap-lib-driving {
    border-bottom-left-radius: 4px;
    border-bottom-right-radius: 4px;
    overflow: hidden;
  }

  .amap-lib-marker-to {
    background: url(http://api.xiongmaodangao.com/images/cake.png) no-repeat !important;
  }

  .amap-lib-marker-from {
    background: none;
    /* background: url(http://api.xiongmaodangao.com/images/xmdg_blue.png) no-repeat !important; */
  }

  .amap-lib-marker-from,
  .amap-lib-marker-mid,
  .amap-lib-marker-to {
    width: 0px !important;
    height: 0px !important;
    color: #e90000;
  }

  .amap-marker-label {
    border: none !important;
    padding: 0 !important;
    background-color: #Fff;
    top: -30px;
    left: -20px;

    .mapcontainter {
      border: 1px solid #91c18f;
      width: 80px;
      background: #91c18f;
      line-height: 24px;
      color: #fff;
      padding: 0 8px;
      position: relative;
    }

    .mapcontainterblue {
      border: 1px solid #68a9eb;
      background: #68a9eb;
      line-height: 24px;
      color: #fff;
      padding: 2px 8px;
      position: relative;
    }

    &::after {
      content: '';
      width: 0;
      height: 0;
      border-width: 10px 10px 0px;
      border-style: solid;
      border-color: transparent transparent #3FB58E;
      position: absolute;
      left: 80px;
      top: -10px;
    }
  }

  .app-container {
    .filter-container {
      padding-right: 20px;

      .flex {
        display: flex;

        .el-form-item {
          margin-bottom: 0 !important;
        }
      }
    }

    .deliverysflex {
      display: flex;
    }

    .main {
      .map-container {
        width: 100%;
        /* height: 550px; */

      }
    }

    .markTips {
      position: absolute;
      top: 50%;
      z-index: 999;
      background: rgba(0, 0, 0, .8);
      color: #fff;
      padding: 10px;
      border-radius: 4px;
      left: 40%;
    }

  }
</style>
